All files / web/src/app/api/classrooms/[classroomId]/entry-prompts route.ts

0% Statements 0/196
0% Branches 0/1
0% Functions 0/1
0% Lines 0/196

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197                                                                                                                                                                                                                                                                                                                                                                                                         
import { and, eq, inArray, lt } from 'drizzle-orm'
import { NextResponse } from 'next/server'
import { db, schema } from '@/db'
import {
  getEnrolledStudents,
  getLinkedParentIds,
  getPresentPlayerIds,
  getTeacherClassroom,
} from '@/lib/classroom'
import { emitEntryPromptCreated } from '@/lib/classroom/socket-emitter'
import { getUserId } from '@/lib/viewer'
import { withAuth } from '@/lib/auth/withAuth'

/**
 * Default expiry time for entry prompts (30 minutes)
 */
const DEFAULT_EXPIRY_MINUTES = 30

/**
 * GET /api/classrooms/[classroomId]/entry-prompts
 * Get pending entry prompts for the classroom (teacher only)
 */
export const GET = withAuth(async (_request, { params }) => {
  try {
    const { classroomId } = (await params) as { classroomId: string }
    const userId = await getUserId()

    // Verify user is the teacher of this classroom
    const classroom = await getTeacherClassroom(userId)
    if (!classroom || classroom.id !== classroomId) {
      return NextResponse.json({ error: 'Not authorized' }, { status: 403 })
    }

    // Get pending prompts for this classroom
    const prompts = await db.query.entryPrompts.findMany({
      where: and(
        eq(schema.entryPrompts.classroomId, classroomId),
        eq(schema.entryPrompts.status, 'pending')
      ),
    })

    // Filter out expired prompts (client-side check)
    const now = new Date()
    const activePrompts = prompts.filter((p) => p.expiresAt > now)

    return NextResponse.json({ prompts: activePrompts })
  } catch (error) {
    console.error('Failed to fetch entry prompts:', error)
    return NextResponse.json({ error: 'Failed to fetch entry prompts' }, { status: 500 })
  }
})

/**
 * POST /api/classrooms/[classroomId]/entry-prompts
 * Create entry prompts for students (teacher only)
 *
 * Body: { playerIds: string[], expiresInMinutes?: number }
 * Returns: { prompts: EntryPrompt[], skipped: { playerId: string, reason: string }[] }
 */
export const POST = withAuth(async (req, { params }) => {
  try {
    const { classroomId } = (await params) as { classroomId: string }
    const userId = await getUserId()
    const body = await req.json()

    // Validate request body
    if (!body.playerIds || !Array.isArray(body.playerIds) || body.playerIds.length === 0) {
      return NextResponse.json({ error: 'Missing or invalid playerIds' }, { status: 400 })
    }

    // Verify user is the teacher of this classroom
    const classroom = await getTeacherClassroom(userId)
    if (!classroom || classroom.id !== classroomId) {
      return NextResponse.json({ error: 'Not authorized' }, { status: 403 })
    }

    // Get teacher's name for the notification
    const teacher = await db.query.users.findFirst({
      where: eq(schema.users.id, userId),
    })
    const teacherName = teacher?.name || 'Your teacher'

    // Get enrolled students for this classroom
    const enrolledStudents = await getEnrolledStudents(classroomId)
    const enrolledPlayerIds = new Set(enrolledStudents.map((s) => s.id))

    // Get currently present students
    const presentPlayerIds = new Set(await getPresentPlayerIds(classroomId))

    // Mark any expired pending prompts as 'expired' so unique constraint allows new ones
    const now = new Date()
    await db
      .update(schema.entryPrompts)
      .set({ status: 'expired' })
      .where(
        and(
          eq(schema.entryPrompts.classroomId, classroomId),
          eq(schema.entryPrompts.status, 'pending'),
          inArray(schema.entryPrompts.playerId, body.playerIds),
          lt(schema.entryPrompts.expiresAt, now) // Only mark actually expired prompts
        )
      )

    // Now query for any truly active (non-expired) pending prompts
    const existingPrompts = await db.query.entryPrompts.findMany({
      where: and(
        eq(schema.entryPrompts.classroomId, classroomId),
        eq(schema.entryPrompts.status, 'pending'),
        inArray(schema.entryPrompts.playerId, body.playerIds)
      ),
    })
    // Filter to only active prompts (not expired)
    const activeExistingPrompts = existingPrompts.filter((p) => p.expiresAt > now)
    const existingPromptPlayerIds = new Set(activeExistingPrompts.map((p) => p.playerId))

    // Calculate expiry time (request override > classroom setting > system default)
    const expiresInMinutes =
      body.expiresInMinutes || classroom.entryPromptExpiryMinutes || DEFAULT_EXPIRY_MINUTES
    const expiresAt = new Date(Date.now() + expiresInMinutes * 60 * 1000)

    // Process each player
    const createdPrompts: (typeof schema.entryPrompts.$inferSelect)[] = []
    const skipped: { playerId: string; reason: string }[] = []

    for (const playerId of body.playerIds) {
      // Check if enrolled
      if (!enrolledPlayerIds.has(playerId)) {
        skipped.push({ playerId, reason: 'not_enrolled' })
        continue
      }

      // Check if already present
      if (presentPlayerIds.has(playerId)) {
        skipped.push({ playerId, reason: 'already_present' })
        continue
      }

      // Check if already has pending prompt
      if (existingPromptPlayerIds.has(playerId)) {
        skipped.push({ playerId, reason: 'pending_prompt_exists' })
        continue
      }

      // Create the entry prompt
      const [prompt] = await db
        .insert(schema.entryPrompts)
        .values({
          teacherId: userId,
          playerId,
          classroomId,
          expiresAt,
        })
        .returning()

      createdPrompts.push(prompt)

      // Get player info for the notification
      const player = await db.query.players.findFirst({
        where: eq(schema.players.id, playerId),
      })

      if (player) {
        // Get parent IDs to notify
        const parentIds = await getLinkedParentIds(playerId)

        // Emit socket event to parents
        await emitEntryPromptCreated(
          {
            promptId: prompt.id,
            classroomId,
            classroomName: classroom.name,
            playerId,
            playerName: player.name,
            playerEmoji: player.emoji,
            teacherName,
            expiresAt,
          },
          parentIds
        )
      }
    }

    return NextResponse.json(
      {
        prompts: createdPrompts,
        skipped,
        created: createdPrompts.length,
        skippedCount: skipped.length,
      },
      { status: 201 }
    )
  } catch (error) {
    console.error('Failed to create entry prompts:', error)
    return NextResponse.json({ error: 'Failed to create entry prompts' }, { status: 500 })
  }
})